import React from 'react';
import {  Modal, Button, notification, message, Form, Input, Upload, Icon} from 'antd';
import FieldConverterFactory from 'components/FieldConverter';
import UEditor from 'components/Ueditor/index.js';
import ajax from 'utils/ajax';
import './articleEdit.less';

let _this = "";
let articleEditForm = "";
class ArticleEditForm extends React.Component{
  state = {
    modelTitle:"",
    modalEditVisible: "",
    previewVisible: false,
    previewImage: "",
    data : "",
  }


  handleEditModalOk = () =>{

  }

  hideEditModal= () =>{

  }

  handleEditModalOk = () =>{

  }

  /**
   * 点击查看图片
   */
  handlePreview = () =>{
    this.setState({"previewVisible" : true});
  }

  /**
   * 关闭弹出的图片框
   */
  handleCancel = () =>{
    this.setState({"previewVisible" : false});
  }

  /**
   * 删除图片
   */
  onRemove = () =>{
    _this.onRemove();
  }

  /**
   * 上传框的文件更改
   * @param info
   */
  onImageFileChange = (info)=>{
    _this.onImageFileChange(info);
  }

  constructor(props) {
    super(props);
    articleEditForm = this;
    _this.setFormState(this.props.form);
    console.log("初始化 form 的数据", this.props.form);
    this.state = {
      // upOpt: ['OPTION_SAVE'],
    };
    // 0 返回file和image 
    // 1 file 
    // 2 image
    this.responseStatus = 2;
  }

  render () {
    const formItems = [];
    var converter = FieldConverterFactory.getConverter(FieldConverterFactory.FormFieldConverter);
    let field = {key: "title", title: "新闻标题", dataType: "varchar", labelCol : { span : 6, pull : 4} , wrapperCol : {span : 18, pull : 4}, placeholder: "请输入新闻标题", rules:[{"message" : "请输入新闻标题", "required" : true}]}
    let fieldHidden = {key: "coverImgId", dataType: "hidden"};
    // let fieldImage = {key: "image", title: "封面图片", dataType: "imageFileUpAndView", imageFileUpUrl : "upload/file", labelCol : { span : 6, pull : 4} , wrapperCol : {span : 18, pull : 4}};
    // let fieldImage = {key: "image", title: "封面图片", dataType: "imageFileUpAndView", imageFileUpUrl : "upload/file", labelCol : { span : 6, pull : 4} , wrapperCol : {span : 18, pull : 4}, rules:[{"message" : "请选择图片", "required" : true}]};
    // let fieldSelect = {key: "articleTypeId", placeholder: "请选择分类", requestSelectValue : this.props.defaultSelect, dataType: "selectByRequestValue", title : "所属分类", rules:[{"message" : "请选择所属分类", "required" : true}], labelCol : { span : 6, pull : 4} , wrapperCol : {span : 18, pull : 4}};
    let alias = {key: "alias", title: "别名", dataType: "varchar", labelCol : { span : 6, pull : 4} , wrapperCol : {span : 18, pull : 4}, placeholder: "请输入别名"}
    formItems.push(converter.convert(this, field));
    formItems.push(converter.convert(this, fieldHidden));
    formItems.push(converter.convert(this, alias));
    // formItems.push(converter.convert(this, fieldImage));
    // formItems.push(converter.convert(this, fieldSelect));
    return (<Form>
      {formItems}
    </Form>)
  }
}

let ArticleEditFormWrapped = "" ;
class ArticleEditModal extends React.Component{

  state = {
    modelTitle:"",
    modalEditVisible: "",
    requestSelectValue : "",
  }

  articleState = {
    article : "",
  }

  ueState = {
    ueItem : "",
  }

  formState = {
    formItem : "",
  }

  getArticleState = () =>{
    return this.articleState;
  }
  setArticleState = (obj) =>{
    this.articleState.article = obj;
  }


  setFormState = (obj) =>{
    this.formState.formItem = obj;
  }

  getFormState = () =>{
    return this.formState.formItem;
  }

  setUeItem = (obj) =>{
    this.ueState = obj;
  }

  getUeItem = () => {
    return this.ueState;
  }

  constructor(props) {
    super(props);
    console.log(this.props.location.query.catId);
    ArticleEditFormWrapped = Form.create()(ArticleEditForm);
    _this = this;
    //请求分类
    this.initArticleValue(props.params.id);
  }

  initArticleValue= (id) =>{
    console.log("编辑数据", id);
    let _this = this;
    if (id) {
      ajax.post({
        url: "/articlemanage/detail",
        params: {id: id},
        async : false,
        success: (res) => {
          let data = res.data.data;
          if (data) {
            _this.setArticleState(data);
          }
        }
      });
    }


  }

  initSelectValue= (id) => {
    let requestSelectValue = this.state.requestSelectValue;
    if (!requestSelectValue && requestSelectValue == "") {
      //如果为空, 则去请求后台数据
      _this = this;
      ajax.post({
        url: "/articlemanage/articleTypeList",
        params: {},
        success: function (res) {
          if (res.data.list && res.data.list.length > 0) {
            let list = res.data.list;
            requestSelectValue = list.map((node) => {
              return ({name: node.name, value: node.id});
            });
            _this.setState({requestSelectValue: requestSelectValue});
          }
        }
      })

    }

    ajax.post({
      url: "/articlemanage/detail",
      params: {id: id},
      async: true,
      success: (res) => {
        let data = res.data.data;
        if (data) {
          //设置页面的值
          this.getFormState().setFieldsValue({
            title: data.title,
            alias: data.alias,
            // articleTypeId: data.catId,
            // coverImgId: data.coverList[0].id,
            // image: data.coverList[0].id
          });
          // this.setState({
          //   catId: data.catId
          // })
          let fileList = data.coverList;
          if(fileList instanceof Array){
            fileList.map((file => {
              file.url = file.imgUrl;
            }));
          }
          articleEditForm.setState({
            fileListSize: 1,
            fileList: fileList,
            // previewImage: data.coverList[0].imgUrl,
            defaultSelectValue: data.articleTypeId,
          });
          setTimeout(() => {
            this.getUeItem().setContent(data.content);
          }, 1000);
        }
      }
    });
  }



  onRemove = () =>{
    delete articleEditForm.state.fileListSize;
    return true;
  }



  onImageFileChange = (info) =>{
    let fileList = info.fileList;

    if (fileList.length > 1) {
      fileList = fileList.slice(-1); //最多只能有一个文件
    }


    if (info.file.response && info.file.status == "done") {
      let fileUrl = "";
      fileList = fileList.map((file) => {
        file.url = file.response.data.imgUrl;
        fileUrl = file.response.data.imgUrl;
        return file;
      });
      let id = info.file.response.data.id;
      this.getFormState().setFieldsValue({coverImgId: id, image : id});
      articleEditForm.setState({ fileListSize : 1, previewImage : fileUrl, });
    }
    articleEditForm.setState({fileList: fileList});
  }

  /**
   * 点击发布
   */
  onPublish = () =>{
    console.log("发布");
    this.save(1);
  }

  /**
   * 点击保存
   */
  onSave = () => {
    console.log("保存");
    this.save(2);
  }

  save = (status) =>{
    let ueItem = this.getUeItem();
    let uEditContent = this.getUeItem().getContent();
    let fieldsValue = this.getFormState().getFieldsValue();
    this.getFormState().validateFields((errors, values)=> {
      if (uEditContent == "" || "请输入哪怕一个字符" == uEditContent) {
        ueItem.setContent("<font color='red'>请输入哪怕一个字符</font>");
        return;
      }

      //开始保存数据
      if (errors == null) {
        values.content = uEditContent.replace(/"([^"]*)"/g, "'$1'");
        values.status = status;
        values.catId = this.props.location.query.catId;
        console.log("保存的数据", values);
        ajax.post({
          url: '/articlemanage/saveArticle',
          params: values,
          success: function (res) {
            if (res.errorCode == 200) {
              message.success('保存成功');
              setTimeout(() => {
                _this.onBack();
              }, 800);
            } else if (res.errorCode == 300) {
              notification.error({
                message: '出错啦!',
                description: res.moreInfo,
                duration: 0,
              });
            }
          }
        })
      }
    });
  }

  /**
   * 更新
   */
  onUpdate = () =>{
    let id = this.props.location.query.id;
    let ueItem = this.getUeItem();
    let uEditContent = this.getUeItem().getContent();
    let fieldsValue = this.getFormState().getFieldsValue();
    this.getFormState().validateFields((errors, values)=> {

      if (uEditContent == "" || "请输入哪怕一个字符" == uEditContent) {
        ueItem.setContent("<font color='red'>请输入哪怕一个字符</font>");
        return;
      }

      //开始保存数据
      if (errors == null) {
        values.content = uEditContent.replace(/"([^"]*)"/g, "'$1'");
        values.id = id;
        values.catId = this.props.location.query.catId;
        console.log("更新的数据", values);
        ajax.post({
          url: '/articlemanage/saveArticle',
          params: values,
          success: function (res) {
            if (res.errorCode == 200) {
              message.success('更新成功');
              setTimeout(() => {
                _this.onBack();
              }, 800);
            } else if (res.errorCode == 300) {
              notification.error({
                message: '出错啦!',
                description: res.moreInfo,
                duration: 0,
              });
            }
          }
        })
      }
    });

  }

  /**
   * 下架
   */
  onChangeState = (status) =>{
    let id = this.props.location.query.id;
    let _this = this;
    ajax.post({
      url: '/articlemanage/updateStatus',
      params: {id :  id, status : status},
      success: function (res) {
        if (res.errorCode == 200) {
          message.success('修改成功');
          _this.setState({isCanOfLine : true});
        } else if (res.errorCode == 300) {
          notification.error({
            message: '出错啦!',
            description: res.moreInfo,
            duration: 0,
          });
        }
      }
    })
  }

  /**
   * 点击返回
   */
  onBack = () => {
    window.location.href = "/cms/manage/index#/cms/manage/ArticleManage/articleTypeList";
  }
  render(){
    let editButtonOfLine = (this.getArticleState().article.status == 1 ? <Button type="primary" onClick={e=>this.onChangeState(2)} disabled={this.state.isCanOfLine}>下架</Button> : <Button type="primary" onClick={e=>this.onChangeState(1)} disabled={this.state.isCanOfLine}>上架</Button>);
    let editButtonUpdate = (<Button type="primary" onClick={this.onUpdate}>更新</Button>);
    let createdButtonSave = (<Button type="primary" onClick={this.onSave}>保存</Button>);
    let createdButtonPUblish = (<Button type="primary" onClick={this.onPublish}>发布</Button>);
    return (<div >
      <div className="editTitleClass">
        <div className="buttonsDivClass">
          <Button type="" onClick={this.onBack}>返回</Button>
          <Button type="primary" disabled="true">预览</Button>
          {this.props.location.query.id ? editButtonOfLine : createdButtonSave}
          {this.props.location.query.id ? editButtonUpdate : createdButtonPUblish}
        </div>
        <span className="editTitleSpan">新增新闻</span>
      </div>
      <ArticleEditFormWrapped defaultSelect={this.state.requestSelectValue}/>
      <div>
      </div>
      <div>
        <span className="contentLabel">正文:</span>
        <div className="content"><UEditor parantItem={this} ></UEditor></div>
        { this.initSelectValue(this.props.location.query.id)}
      </div>
    </div>);
  }
}

export default ArticleEditModal;
